import com.formdev.flatlaf.FlatDarkLaf;

import javax.swing.*;
import java.awt.*;
import java.util.List;

/**
 * 游戏爬取应用
 */
public class MainFrame extends JFrame {
	private static int WIDTH = 600;
	private static int HEIGHT = 500;

	private JTextField searchField;
	private JButton searchButton;
	private JList<String> gameList;
	private JTextArea downloadArea;
	private JButton buyButton;

	private List<GameDetail> gameDetails;
	// private Vector<String> vector;
	private DefaultListModel<String> listModel;

	private String cookie;

	public MainFrame() {
		try {
			// 登录
			cookie = GameDownloadCrawl.getCookie("1580313824", "15803138248818");
		} catch (RuntimeException e) {
			downloadArea.setText(e.getMessage());
		}
		initComponents();
		setListeners();
		initView();
	}

	public static void main(String[] args) {
		FlatDarkLaf.setup();
		EventQueue.invokeLater(() -> new MainFrame().setVisible(true));
	}

	private void initComponents() {
		searchField = new JTextField(30);
		searchButton = new JButton("搜索");
		listModel = new DefaultListModel<>();
		gameList = new JList<>(listModel);
		gameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);//单选
		downloadArea = new JTextArea();
		buyButton = new JButton("购买");
		buyButton.setPreferredSize(new Dimension(200, 30));
	}

	private void setListeners() {
		// 搜索
		searchButton.addActionListener(e -> {
			listModel.clear();
			try {
				// 搜索游戏
				gameDetails = GameDownloadCrawl.gameSearch(cookie, searchField.getText());
			} catch (RuntimeException ex) {
				downloadArea.setText(ex.getMessage());
			}
			gameDetails.forEach(gameDetail -> listModel.addElement(gameDetail.getTitle()));
		});

		// 购买
		buyButton.addActionListener(e -> {
			GameDetail selectedGame = gameDetails.get(gameList.getSelectedIndex());
			try {
				// 购买
				GameDownloadCrawl.gameBuy(selectedGame, cookie);
				// 获取下载链接
				GameDownloadCrawl.getDownload(selectedGame);
				downloadArea.setText(selectedGame.getUrl());
			} catch (RuntimeException ex) {
				downloadArea.setText(ex.getMessage());
			}
		});
	}

	private void initView() {
		Container contentPane = getContentPane();
		// 顶部
		JPanel topPanel = new JPanel();
		topPanel.add(searchField);
		topPanel.add(searchButton);
		contentPane.add(topPanel, BorderLayout.NORTH);

		// 中部
		JPanel midPanel = new JPanel(new BorderLayout());
		JScrollPane listScrollPane = new JScrollPane(gameList);
		listScrollPane.setPreferredSize(new Dimension(WIDTH - 8, 350));
		midPanel.add(listScrollPane);
		JPanel buyPanel = new JPanel();
		buyPanel.add(buyButton);
		midPanel.add(buyPanel, BorderLayout.SOUTH);
		contentPane.add(midPanel);

		// 底部
		JScrollPane scrollPane = new JScrollPane(downloadArea);
		scrollPane.setPreferredSize(new Dimension(WIDTH - 8, 150));
		contentPane.add(scrollPane, BorderLayout.SOUTH);

		setTitle("游戏下载地址爬取");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(WIDTH, HEIGHT);
		setLocationRelativeTo(null);
	}
}
